import axios from "axios"
import { notification, Spin } from 'antd'
import ReactDOM from 'react-dom/client'

const request = axios.create({
    baseURL: "http://localhost:5173/mylearnblog/api",
    timeout: 5 * 60 * 1000, // 请求 5分钟 超时
    headers: {
        "Content-Type": "application/json",
    },
})

// 当前请求数量
let httpCount: number = 0
const showLoading = () => {
    if(httpCount === 0) {
        let dom = document.createElement('div')
        dom.setAttribute('id', 'app-fullsreen-loading')
        document.body.appendChild(dom)
        ReactDOM.createRoot(document.getElementById('app-fullsreen-loading')!).render(<Spin fullscreen/>)
    }
    httpCount++ 
}
const hideLoading = () => {
    httpCount--
    if (httpCount === 0) {
        document.body.removeChild(document.getElementById('app-fullsreen-loading'))
    }
}

// 添加请求拦截器
request.interceptors.request.use((config: any) => {
    const loading: boolean = config.loading ?? true
    if(loading) {
        showLoading()
    }
    // const token = sessionStorage.getItem("token")
    const token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MDQ4NTQzNjEsInVzZXIiOnsidWlkIjoidWlkXzE3MDQxMTU2Mzg1MDQiLCJ1c2VybmFtZSI6IjEyMyJ9fQ.zmiPxlqtxD7RBNNenxXB5wfoqP2YFdVgqU5peSmhHXg'
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
}, (error: any) => {
    return Promise.reject(error)
})

// 响应拦截器
request.interceptors.response.use((response: any) => {          
    // 2 开头的状态码都会触发该函数
    hideLoading()
    return response.data
}, (error: any) => {
    hideLoading()
    // 非 2 开头的状态码都会触发该函数
    if (error.response) {
        switch (error.response.status) {
            case 401:
                notification['error']({
                    message: '403 连接失败',
                })
                break;
            case 403:
                notification['error']({
                    message: '403 连接失败',
                })
                break;
            case 404:
                notification['error']({
                    message: '404 连接失败',
                })
                break;
            case 500:
                notification['error']({
                    message: '500 连接失败',
                })
                break;
        }
    }
    return Promise.reject(error)
})

export default request 


